import { ref, reactive } from 'vue';
import { getSettingsByCategory } from '@/api/systemSettings';

// 创建一个单例配置服务
class ConfigService {
  constructor() {
    // 初始化状态
    this.initialized = false;
    
    // 店铺信息设置
    this.storeSettings = reactive({
      name: '哈喽啤鲜生',
      address: '北京市朝阳区国贸中心',
      phone: '010-12345678',
      openTime: '',
      closeTime: '',
      taxNumber: '',
      slogan: '精酿啤酒，鲜活生活',
      location: '国贸360店', // 店铺位置，用作副标题
      qrCodeUrl: '' // 二维码URL
    });
    
    // 小票打印设置
    this.receiptSettings = reactive({
      width: '58',
      fontSize: 'medium',
      header: '哈喽啤鲜生国贸店',
      footer: '谢谢惠顾，欢迎再次光临！',
      printLogo: true,
      printQrCode: true,
      printOrderNumber: true,
      directPrint: false, // 是否直接打印，不显示预览
      productDisplay: 'simple'
    });
    
    // 界面偏好设置
    this.interfaceSettings = reactive({
      theme: 'light',
      primaryColor: '#409EFF',
      density: 'default',
      defaultPage: '/pos',
      notifications: {
        inventory: true,
        orders: true
      }
    });
    
    // 加载状态
    this.loading = reactive({
      store: false,
      receipt: false,
      interface: false
    });
  }
  
  // 初始化配置服务
  async init() {
    if (this.initialized) return;
    
    try {
      // 从localStorage读取界面设置
      this.loadInterfaceSettingsFromLocal();
      
      // 应用界面设置
      this.applyInterfaceSettings();
      
      // 从服务器加载设置
      await Promise.all([
        this.loadStoreSettings(),
        this.loadReceiptSettings(),
        this.loadInterfaceSettings()
      ]);
      
      this.initialized = true;
      console.log('配置服务初始化完成');
    } catch (error) {
      console.error('配置服务初始化失败:', error);
    }
  }
  
  // 从localStorage读取界面设置
  loadInterfaceSettingsFromLocal() {
    const theme = localStorage.getItem('theme');
    const primaryColor = localStorage.getItem('primaryColor');
    const density = localStorage.getItem('density');
    const defaultPage = localStorage.getItem('defaultPage');

    if (theme) this.interfaceSettings.theme = theme;
    if (primaryColor) this.interfaceSettings.primaryColor = primaryColor;
    if (density) this.interfaceSettings.density = density;
    if (defaultPage) this.interfaceSettings.defaultPage = defaultPage;
  }
  
  // 应用界面设置
  applyInterfaceSettings() {
    // 应用主题模式
    document.documentElement.setAttribute('data-theme', this.interfaceSettings.theme);
    
    // 应用主题颜色
    document.documentElement.style.setProperty('--el-color-primary', this.interfaceSettings.primaryColor);
    

    
    // 应用显示密度
    document.body.setAttribute('data-density', this.interfaceSettings.density);
  }
  
  // 加载店铺信息设置
  async loadStoreSettings() {
    this.loading.store = true;
    try {
      const response = await getSettingsByCategory('frontend.store');
      if (response && response.success) {
        const data = response.data || {};
        
        this.storeSettings.name = data.name?.value || this.storeSettings.name;
        this.storeSettings.address = data.address?.value || this.storeSettings.address;
        this.storeSettings.phone = data.phone?.value || this.storeSettings.phone;
        
        // 直接使用字符串格式的时间值，让时间选择器组件自己处理
        this.storeSettings.openTime = data.openTime?.value || '';
        this.storeSettings.closeTime = data.closeTime?.value || '';
        
        this.storeSettings.taxNumber = data.taxNumber?.value || this.storeSettings.taxNumber;
        this.storeSettings.slogan = data.slogan?.value || this.storeSettings.slogan;
        this.storeSettings.location = data.location?.value || this.storeSettings.location;
        this.storeSettings.qrCodeUrl = data.qrCodeUrl?.value || this.storeSettings.qrCodeUrl;
      }
    } catch (error) {
      console.error('加载店铺设置失败:', error);
    } finally {
      this.loading.store = false;
    }
  }
  
  // 加载小票打印设置
  async loadReceiptSettings() {
    this.loading.receipt = true;
    try {
      const response = await getSettingsByCategory('frontend.receipt');
      if (response && response.success) {
        const data = response.data || {};

        // 只有当数据库中有值时才更新，否则保持当前值
        if (data.width?.value !== undefined) {
          this.receiptSettings.width = data.width.value;
        }
        if (data.fontSize?.value !== undefined) {
          this.receiptSettings.fontSize = data.fontSize.value;
        }
        if (data.header?.value !== undefined) {
          this.receiptSettings.header = data.header.value;
        }
        if (data.footer?.value !== undefined) {
          this.receiptSettings.footer = data.footer.value;
        }
        if (data.printLogo?.value !== undefined) {
          this.receiptSettings.printLogo = data.printLogo.value === 'true';
        }
        if (data.printQrCode?.value !== undefined) {
          this.receiptSettings.printQrCode = data.printQrCode.value === 'true';
        }
        if (data.printOrderNumber?.value !== undefined) {
          this.receiptSettings.printOrderNumber = data.printOrderNumber.value === 'true';
        }
        if (data.directPrint?.value !== undefined) {
          this.receiptSettings.directPrint = data.directPrint.value === 'true';
        }
        if (data.productDisplay?.value !== undefined) {
          this.receiptSettings.productDisplay = data.productDisplay.value;
        }

        console.log('小票设置加载成功:', this.receiptSettings);
      } else {
        console.log('未找到小票设置，使用默认值');
      }
    } catch (error) {
      console.error('加载小票设置失败:', error);
    } finally {
      this.loading.receipt = false;
    }
  }
  
  // 加载界面偏好设置
  async loadInterfaceSettings() {
    this.loading.interface = true;
    try {
      const response = await getSettingsByCategory('frontend.interface');
      if (response && response.success) {
        const data = response.data || {};
        
        // 只更新服务器上存在的设置，保留本地设置的优先级
        if (data.theme?.value) this.interfaceSettings.theme = data.theme.value;
        if (data.primaryColor?.value) this.interfaceSettings.primaryColor = data.primaryColor.value;

        if (data.density?.value) this.interfaceSettings.density = data.density.value;
        if (data.defaultPage?.value) this.interfaceSettings.defaultPage = data.defaultPage.value;
        if (data['notifications.inventory']?.value !== undefined) {
          this.interfaceSettings.notifications.inventory = data['notifications.inventory'].value === 'true';
        }
        if (data['notifications.orders']?.value !== undefined) {
          this.interfaceSettings.notifications.orders = data['notifications.orders'].value === 'true';
        }
        
        // 保存到localStorage
        this.saveInterfaceSettingsToLocal();
        
        // 重新应用设置
        this.applyInterfaceSettings();
      }
    } catch (error) {
      console.error('加载界面设置失败:', error);
    } finally {
      this.loading.interface = false;
    }
  }
  
  // 保存界面设置到localStorage
  saveInterfaceSettingsToLocal() {
    localStorage.setItem('theme', this.interfaceSettings.theme);
    localStorage.setItem('primaryColor', this.interfaceSettings.primaryColor);

    localStorage.setItem('density', this.interfaceSettings.density);
    localStorage.setItem('defaultPage', this.interfaceSettings.defaultPage);
  }
  
  // 获取店铺名称
  getStoreName() {
    return this.storeSettings.name;
  }
  
  // 获取小票设置
  getReceiptSettings() {
    return this.receiptSettings;
  }
  
  // 获取界面设置
  getInterfaceSettings() {
    return this.interfaceSettings;
  }
  
  // 获取店铺设置
  getStoreSettings() {
    return this.storeSettings;
  }

  // 获取初始化状态
  isInitialized() {
    return this.initialized;
  }

  // 通用配置获取方法
  async fetchConfig(configKey, apiEndpoint) {
    try {
      // 首先尝试从localStorage获取缓存
      const cacheKey = `hello_beer_${configKey}`;
      const timestampKey = `${cacheKey}_timestamp`;
      const cached = localStorage.getItem(cacheKey);
      const timestamp = localStorage.getItem(timestampKey);

      // 检查缓存是否有效（5分钟内）
      if (cached && timestamp) {
        const cacheAge = Date.now() - parseInt(timestamp);
        if (cacheAge < 5 * 60 * 1000) { // 5分钟
          console.log(`使用缓存的${configKey}数据`);
          return JSON.parse(cached);
        }
      }

      // 缓存无效或不存在，从API获取
      const api = (await import('@/utils/api')).default;
      const response = await api.get(apiEndpoint);

      if (response.data && response.data.status === 'success') {
        const data = response.data.data;

        // 缓存数据
        localStorage.setItem(cacheKey, JSON.stringify(data));
        localStorage.setItem(timestampKey, Date.now().toString());

        console.log(`成功获取${configKey}数据:`, data);
        return data;
      } else {
        throw new Error(`API返回错误: ${response.data?.message || '未知错误'}`);
      }
    } catch (error) {
      console.error(`获取${configKey}数据出错:`, error);

      // 如果API失败，尝试使用缓存数据（即使过期）
      const cacheKey = `hello_beer_${configKey}`;
      const cached = localStorage.getItem(cacheKey);
      if (cached) {
        console.log(`API失败，使用过期缓存的${configKey}数据`);
        return JSON.parse(cached);
      }

      // 如果没有缓存，返回默认数据
      return this.getDefaultConfig(configKey);
    }
  }

  // 获取默认配置数据
  getDefaultConfig(configKey) {
    const defaults = {
      channels: [
        { id: 1, name: '堂食', icon: 'restaurant' },
        { id: 3, name: '外卖', icon: 'takeaway' },
        { id: 7, name: '美团', icon: 'meituan' },
        { id: 9, name: '饿了么', icon: 'eleme' }
      ],
      paymentMethods: [
        { id: 1, name: '现金', icon: 'money' },
        { id: 2, name: '微信支付', icon: 'wechat' },
        { id: 3, name: '支付宝', icon: 'alipay' },
        { id: 4, name: '其他', icon: 'gift' }
      ],
      categories: []
    };

    console.log(`使用硬编码${configKey}数据作为备份`);
    return defaults[configKey] || [];
  }
}

// 创建单例
const configService = new ConfigService();

export default configService; 